package com.focusai.efairy.ui.activity.more;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.focusai.efairy.EFApplication;
import com.focusai.efairy.R;
import com.focusai.efairy.config.AppConfig;
import com.focusai.efairy.model.manager.CacheManager;
import com.focusai.efairy.model.request.ChangUserInfoRequest;
import com.focusai.efairy.model.request.GetUserDetailInfoRequest;
import com.focusai.efairy.model.user.UpLoadUserInfo;
import com.focusai.efairy.model.user.UserDetailInfo;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Image.ImageLoaderFactory;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.Ipresenter.IUpLoadFilePresenter;
import com.focusai.efairy.ui.activity.ChangePasswdActivity;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.ui.iview.IUpLoadFileView;
import com.focusai.efairy.ui.presenter.UpLoadFilePresenter;
import com.focusai.efairy.utils.PictureUtil;
import com.focusai.efairy.utils.log.Log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by luo_guangwen on 2017/8/17.
 */

public class UserDetailInfoActivity extends SwipeBackBaseActivity implements View.OnClickListener, IUpLoadFileView {
    private final int requestcode_getPhoto = 0;// 获取相片
    private final int requestcode_takePhoto = 1;// 拍摄相片
    private final int requestcode_cutPhoto = 2;// 裁剪相片

    private TextView tvName;
    private TextView tvCompany;
    private TextView tvAddress;
    private TextView tvPhone;
    private TextView tvEmail;
    private TextView tvProvider;
    private ImageView imgAvater;

    private String photoPath; //图片保存的路径
    private IUpLoadFilePresenter presenter;
    private File file;
    private Uri uri = null;
    private UpLoadUserInfo upLoadUserInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_user_detail);
        initView();
        setDefaultValues();
        loadData();
    }

    @Override
    public void initTitte() {
        getCenterTextView().setText(R.string.user_info);
    }

    @Override
    protected void initView() {
        findView(R.id.user_name_llayout).setOnClickListener(this);
        findView(R.id.user_avatar_llayout).setOnClickListener(this);
        findView(R.id.user_company_llayout).setOnClickListener(this);
        findView(R.id.user_address_llayout).setOnClickListener(this);
        findView(R.id.user_email_llayout).setOnClickListener(this);
        findView(R.id.user_passwd_llayout).setOnClickListener(this);
        tvName = findView(R.id.tv_user_name);
        tvCompany = findView(R.id.tv_user_company);
        tvAddress = findView(R.id.tv_user_address);
        tvPhone = findView(R.id.tv_user_phone);
        tvEmail = findView(R.id.tv_user_email);
        tvProvider = findView(R.id.tv_user_provider);
        imgAvater = findView(R.id.iv_avater);
    }

    @Override
    protected void setDefaultValues() {
        tvName.setText(CacheManager.getUserName());
        ImageLoaderFactory.getImageLoader().loadImage(mContext, imgAvater, CacheManager.getUserAvater());
        presenter = new UpLoadFilePresenter();
        setResult(RESULT_OK);
    }

    @Override
    public void onClick(View v) {
        Intent userIntent;
        switch (v.getId()) {
            case R.id.user_avatar_llayout:
                showSlectPictureDialog();
                break;
            case R.id.user_name_llayout:
                userIntent = new Intent(getContext(), UserChangeNameActivity.class);
                userIntent.putExtra(UserChangeNameActivity.EDIT_TYPE, UserChangeNameActivity.EDIT_NAME);
                userIntent.putExtra(UserChangeNameActivity.USER_INFO_ENTRY, upLoadUserInfo);
                startActivityForResult(userIntent, UserChangeNameActivity.EDIT_NAME);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
                break;
            case R.id.user_company_llayout:
                userIntent = new Intent(getContext(), UserChangeNameActivity.class);
                userIntent.putExtra(UserChangeNameActivity.EDIT_TYPE, UserChangeNameActivity.EDIT_COMPANY);
                userIntent.putExtra(UserChangeNameActivity.USER_INFO_ENTRY, upLoadUserInfo);
                startActivityForResult(userIntent, UserChangeNameActivity.EDIT_COMPANY);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
                break;
            case R.id.user_address_llayout:
                userIntent = new Intent(getContext(), UserChangeNameActivity.class);
                userIntent.putExtra(UserChangeNameActivity.EDIT_TYPE, UserChangeNameActivity.EDIT_COMPANY_ADD);
                userIntent.putExtra(UserChangeNameActivity.USER_INFO_ENTRY, upLoadUserInfo);
                startActivityForResult(userIntent, UserChangeNameActivity.EDIT_COMPANY_ADD);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
                break;
            case R.id.user_email_llayout:
                userIntent = new Intent(getContext(), UserChangeNameActivity.class);
                userIntent.putExtra(UserChangeNameActivity.EDIT_TYPE, UserChangeNameActivity.EDIT_COMPANY_EMAIL);
                userIntent.putExtra(UserChangeNameActivity.USER_INFO_ENTRY, upLoadUserInfo);
                startActivityForResult(userIntent, UserChangeNameActivity.EDIT_COMPANY_EMAIL);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
                break;
            case R.id.user_passwd_llayout:
                Intent cIntent = new Intent(getContext(), ChangePasswdActivity.class);
                startActivity(cIntent);
                break;
            default:
                break;
        }
    }

    @Override
    protected void loadData() {
        HttpManager.getInstance().sendRequest(new GetUserDetailInfoRequest(new Response.Listener<UserDetailInfo>() {
            @Override
            protected void onSuccess(UserDetailInfo response) {
                if (response != null) {
                    tvName.setText(response.getEfairyuser_nickname());
                    ImageLoaderFactory.getImageLoader().loadImage(mContext, imgAvater, response.getEfairyuser_headimg_url());
                    CacheManager.setUserName(response.getEfairyuser_nickname());
                    CacheManager.setUserAvater(response.getEfairyuser_headimg_url());
                    tvPhone.setText(response.getEfairyuser_phonenumber());
                    tvProvider.setText(response.getEfairyuser_device_supplier());
                    tvCompany.setText(response.getEfairyuser_company());
                    tvAddress.setText(response.getEfairyuser_company_address());
                    tvEmail.setText(response.getEfairyuser_email());
                    upLoadUserInfo = new UpLoadUserInfo();
                    upLoadUserInfo.setEfairyuser_company(response.getEfairyuser_company() == null ? "" : response.getEfairyuser_company());
                    upLoadUserInfo.setEfairyuser_company_address(response.getEfairyuser_company_address() == null ? "" : response.getEfairyuser_company_address());
                    upLoadUserInfo.setEfairyuser_headimg_url(response.getEfairyuser_headimg_url() == null ? "" : response.getEfairyuser_headimg_url());
                    upLoadUserInfo.setEfairyuser_nickname(response.getEfairyuser_nickname() == null ? "" : response.getEfairyuser_nickname());
                    upLoadUserInfo.setEfairyuser_email(response.getEfairyuser_email() == null ? "" : response.getEfairyuser_email());
                }
            }

            @Override
            protected void onFail(NetworkException exception) {

            }
        }));
    }

    private void showSlectPictureDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_select_img_dialog, null);
        builder.setView(view);
        builder.setCancelable(true);
        final AlertDialog alertDialog = builder.create();
        view.findViewById(R.id.tv_take_picture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alertDialog.isShowing())
                    alertDialog.dismiss();
                getPicFromCapture();
            }
        });
        view.findViewById(R.id.tv_select_picture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alertDialog.isShowing())
                    alertDialog.dismiss();
                getPicFromContent();
            }
        });
        alertDialog.show();
    }

    // 拍照
    private void getPicFromCapture() {
        createFilePhoto();
        PictureUtil.openCameraCapture(UserDetailInfoActivity.this, requestcode_takePhoto, file);
    }

    public void createFilePhoto() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        File tempFile = null;
        String index = "";
        for (int i = 0; i < 100; i++) {
            index = "_" + i; // try to find a unique filename
            tempFile = new File(AppConfig.IMAGE_PATH, dateFormat.format(date) + index + ".jpg");
            if (!tempFile.exists()) {
                break;
            }
        }
        file = tempFile;
    }

    // 获取图片
    private void getPicFromContent() {
        Intent intent = PictureUtil.getPicFromSDCard(mContext);
        if (intent != null) {
            try {
                startActivityForResult(intent, requestcode_getPhoto);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    private void saveUserIcon() {
        if (file != null) {
            updateUserIcon(file.getPath());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case requestcode_getPhoto:
                    createFilePhoto();
                    uri = data.getData();
                    Intent intent = PictureUtil.cameraCrop(mContext.getApplicationContext(), file, uri, false);
                    startActivityForResult(intent, requestcode_cutPhoto);
                    break;
                case requestcode_takePhoto:
                    Intent tIntent;
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        String authority = "com.focusai.efairy.provider.fileprovider";
                        if (EFApplication.isCciotApp()) {
                            authority = "com.focusai.cciot.provider.fileprovider";
                        }
                        tIntent = PictureUtil.cameraCrop(mContext.getApplicationContext(), file,
                                FileProvider.getUriForFile(mContext, authority, file), true);
                    } else {
                        File filebg = new File(file.getAbsolutePath() + ".tmp");
                        file.renameTo(filebg);
                        createFilePhoto();
                        tIntent = PictureUtil.cameraCrop(mContext.getApplicationContext(), file, Uri.fromFile(filebg), true);
                    }
                    startActivityForResult(tIntent, requestcode_cutPhoto);
                    break;
                case requestcode_cutPhoto:
                    if (file != null) {
                        saveUserIcon();
                    }
                    break;
                case UserChangeNameActivity.EDIT_NAME:
                case UserChangeNameActivity.EDIT_COMPANY:
                case UserChangeNameActivity.EDIT_COMPANY_ADD:
                case UserChangeNameActivity.EDIT_COMPANY_EMAIL:
                    loadData();
                    break;
                default:
                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onUpLoadFileSeccuss(final String url) {
        if (upLoadUserInfo == null) {
            showToast("修改信息失败");
            return;
        }
        upLoadUserInfo.setEfairyuser_headimg_url(url);

        HttpManager.getInstance().sendRequest(new ChangUserInfoRequest(upLoadUserInfo, new Response.Listener<Integer>() {
            @Override
            protected void onSuccess(Integer response) {
                if (response != null && response == 200) {
                    ImageLoaderFactory.getImageLoader().loadImage(mContext, imgAvater, url);
                    CacheManager.setUserAvater(url);
                }
                closeSingleDialog();
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
            }
        }));
        Log.D("TEST", url);
    }

    @Override
    public void onUpLoadFileFail(String errormsg) {
        closeSingleDialog();
        showToastOnUiThread(errormsg);
    }

    private void updateUserIcon(String filePath) {
        showSingleDialog("正在提交用户头像信息,请稍等...");
        presenter.upLoadFile(filePath, this);
    }
}
